<template>
  <view class="order-closure-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="异常订单列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <view class="header-bar">
            <view class="header-bar-location" @click="showTimePicker = true">
              <text class="title">时间</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
            <view class="header-bar-location" @click="showOwnPicker = true">
              <text class="title">{{ isOwn === 1 ? '本人' : '全部' }}</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
            <view class="time-picker">
              <text class="title"></text>
              <uni-datetime-picker type="daterange" :border="false"></uni-datetime-picker>
            </view>
            <up-picker :show="showTimePicker" :columns="columns" :closeOnClickOverlay="true"
              @confirm="showTimePicker = false" @cancel="showTimePicker = false"
              @close="showTimePicker = false"></up-picker>
            <up-picker :show="showOwnPicker" :columns="ownColumns" :closeOnClickOverlay="true"
              @confirm="handleOwnConfirm" @cancel="showOwnPicker = false"
              @close="showOwnPicker = false"></up-picker>
          </view>

          <up-search v-model="keyword" :clearabled="true" :showAction="false" placeholder="请输入关键字" @search="handleSearch"></up-search>
          <up-tabs :list="tabsList" :scrollable="false" @change="handleTabChange"></up-tabs>
        </up-sticky>
      </template>

      <view class="order-closure-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              订单号：<text class="number">{{ item.orderNo || '-' }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">
                  状态
                </text>
                <view class="value">
                  <view class="item-tag">
                    <up-tag :text="getStatusText(item.auditStatus)" :type="getStatusType(item.auditStatus)"></up-tag>
                  </view>
                </view>
              </view>
              <view class="item">
                <text class="label">
                  车牌号：
                </text>
                <text class="value">
                  {{ item.carPlate || '-' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  异常类型：
                </text>
                <text class="value">
                  {{ getErrorTypeText(item.errorType) }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  异常时间：
                </text>
                <text class="value">
                  {{ item.createTime || '-' }}
                </text>
              </view>
              <!-- 停车位置 -->
              <view class="item">
                <text class="label">
                  停车位置：
                </text>
                <text class="value">
                  {{ item.veName || '-' }}{{ item.beNo ? `（${item.beNo}）` : '' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  驶入时间：
                </text>
                <text class="value">
                  {{ item.inTime || '-' }}
                </text>
              </view>
              <view class="item" v-if="item.outTime">
                <text class="label">
                  出场时间：
                </text>
                <text class="value">
                  {{ item.outTime }}
                </text>
              </view>
              <view class="item" v-if="item.errorRemark">
                <text class="label">
                  异常原因：
                </text>
                <text class="value">
                  {{ item.errorRemark }}
                </text>
              </view>
            </view>
            <view class="card-footer">
              <view class="checkbox-box">
              </view>
              <view class="operate">
                <up-button v-if="item.auditStatus === 0" type="primary" text="处理异常" class="custom-style" @click="handleGo(item)"></up-button>
                <up-button v-else type="info" text="查看详情" class="custom-style" @click="handleView(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <OrderAbnormalModal v-model:show="show" :type="type" :row-data="editingData" @success="handleSuccess" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { getErrorOrderList } from '@/api';
import OrderAbnormalModal from './components/OrderAppealModal.vue'

const { bool: show, setTrue: openModal } = useBoolean();
const type = ref('add')
const editingData = ref({})

const showTimePicker = ref(false);
const showOwnPicker = ref(false);
const columns = reactive([
  ['近7天', '近1个月', '近3个月', '近6个月', '近1年'],
]);
const ownColumns = reactive([
  ['全部', '本人'],
]);

// 处理是否本人选择
const handleOwnConfirm = (e) => {
  const selectedValue = e.detail.value[0];
  isOwn.value = selectedValue === '本人' ? 1 : 0;
  showOwnPicker.value = false;
  
  // 重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
}

// 处理搜索
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
}

// 选项卡数据  
const tabsList = [
  { name: '全部' },
  { name: '待审核' },
  { name: '已审核' },
];
const currentTab = ref(0);

// z-paging 组件引用
const paging = ref(null)

// 当前显示的列表数据
const currentList = ref([])

const handleAdd = () => {
  type.value = 'add'
  openModal()
}

const handleGo = (item: any) => {
  type.value = 'edit'
  editingData.value = item
  openModal()
}

const handleView = (item: any) => {
  // 查看详情，只读模式
  uni.showToast({
    title: '该订单已处理',
    icon: 'none'
  })
}

// 处理成功后刷新列表
const handleSuccess = () => {
  // 刷新列表数据
  paging.value.reload();
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待处理',
    1: '处理中',
    2: '已处理',
    3: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info'
  }
  return typeMap[status] || 'default'
}

// 获取异常类型文本
const getErrorTypeText = (type) => {
  const typeMap = {
    0: '设备检测异常',
    1: '设备离线',
    2: '其他异常'
  }
  return typeMap[type] || '未知异常'
}

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentTab.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentTab.value = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}


// 搜索关键词
const keyword = ref('');
// 是否本人
const isOwn = ref(0);

// 获取异常订单列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize, currentTab.value)

  const params = {
    pageNum: pageNo,
    pageSize,
    keyword: keyword.value,
    isOwn: isOwn.value
  }

  await fetchList(params)
};

const fetchList = async (params) => {
  try {
    // 根据当前选中的tab设置isAuthor参数
    // -1:全部 0:待审核 1:已审核
    const isAuthor = currentTab.value === 0 ? -1 : currentTab.value === 1 ? 0 : 1;
    
    const result: any = await getErrorOrderList({ 
      ...params, 
      isAuthor 
    })
    const data = result.data
    paging.value.complete(data.records || [])
  } catch (error) {
    console.error('获取异常订单列表失败', error)
    paging.value.complete(false)
  }
}

// 审核操作
const handleVerify = (row: any) => {
  // 跳转到审核页逻辑
  console.log('审核操作:', row);
};

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
  })
});
</script>

<style scoped lang="scss">
.order-closure-list {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0rpx 20rpx 30rpx;

  &-item {
    display: flex;
    flex: 1;
    align-items: center;
    text-align: center;

    .item-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }

    .arrow-icon {
      width: 30rpx;
      height: 30rpx;
    }
  }

  .waiting-count {
    font-weight: 500;
    font-size: 24rpx;
    color: #333333;
    display: flex;
    align-items: center;

    text {
      font-weight: bold;
      font-size: 36rpx;
      color: #fe6000;
      margin-left: 10rpx;
    }
  }
}

.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0rpx 20rpx 30rpx;

  .time-picker {
    width: 400rpx;
    display: flex;
    align-items: center;

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }
  }

  &-location {
    display: flex;
    align-items: center;

    .location-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }

    .arrow-icon {
      width: 30rpx;
      height: 30rpx;
    }
  }

  .waiting-count {
    font-weight: 500;
    font-size: 24rpx;
    color: #333333;
    display: flex;
    align-items: center;

    text {
      font-weight: bold;
      font-size: 36rpx;
      color: #fe6000;
      margin-left: 10rpx;
    }
  }
}

/* 列表统计 */
.list-statistics {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
}

.list-statistics .item {
  flex: 1 1 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.list-statistics .label {
  font-size: 14px;
  color: #666;
}

.list-statistics .value {
  font-size: 18px;
  font-weight: bold;
  color: #e9710f;
}
</style>